package com.gjy.util;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-09 10:18:49
 */
public final class JdbcUtil {

    private static final Connection CONNECTION;

    static {
        String path = "D:\\code\\java\\special-topic\\encryption\\src\\main\\resources\\mysql.properties";
        try (InputStream is = Files.newInputStream(Paths.get(path))) {
            Properties properties = new Properties();
            properties.load(is);
            String driver = properties.getProperty("driver");
            Class.forName(driver);
            String url = properties.getProperty("url");
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");
            CONNECTION = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static ResultSet select(String table, String[] fields) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("SELECT").append("\t");
            for (int i = 0; i < fields.length; i++) {
                sb.append(fields[i]);
                if (i != fields.length - 1) {
                    sb.append(", ");
                }
            }
            sb.append(" FROM ").append(table);
            PreparedStatement ps = CONNECTION.prepareStatement(sb.toString());
            return ps.executeQuery();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static ResultSet select(String table, String[] fields, Integer fetch) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("SELECT").append("\t");
            for (int i = 0; i < fields.length; i++) {
                sb.append(fields[i]);
                if (i != fields.length - 1) {
                    sb.append(", ");
                }
            }
            sb.append(" FROM ").append(table);
            PreparedStatement ps = CONNECTION.prepareStatement(sb.toString());
            ps.setFetchSize(fetch);
            return ps.executeQuery();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
